function varargout = DrawSpt(varargin)
% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

% Edit the above text to modify the response to help DrawSpt

% Last Modified by GUIDE v2.5 14-Aug-2011 10:40:31

%TODO: add 'Choose' top string in comboboxes, ignore it when selecting data
%and when updating control points, set Value to 1 if possible.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DrawSpt_OpeningFcn, ...
                   'gui_OutputFcn',  @DrawSpt_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before DrawSpt is made visible.
function DrawSpt_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for DrawSpt
handles.output = hObject;
parent=get(handles.figure1,'UserData');
handles.Path=parent.SetupWidget.getProjectPath();
axes(handles.axes1); %#ok<MAXES>
axis off;
axes(handles.axes3); %#ok<MAXES>
axis off;
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes DrawSpt wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = DrawSpt_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in PB_Image.
function PB_Image_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on selection change in CB_Image.
function CB_Image_Callback(hObject, eventdata, handles)
% hObject    handle to CB_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns CB_Image contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_Image


% --- Executes during object creation, after setting all properties.
function CB_Image_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_Image (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function TL_Project_Callback(hObject, eventdata, handles)
% hObject    handle to TL_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of TL_Project as text
%        str2double(get(hObject,'String')) returns contents of TL_Project as a double


% --- Executes during object creation, after setting all properties.
function TL_Project_CreateFcn(hObject, eventdata, handles)
% hObject    handle to TL_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in PB_Project.
function PB_Project_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Project (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%load folder with output data (OUT)
outputdir=uigetdir(handles.Path,'Select folder with output data (OUT)');
set(handles.TL_Project,'String',outputdir);
if ~isempty(outputdir)
    %grab only first subrun of each run.
    Aux=dir(fullfile(outputdir,'01-*.SPC')); 
    if isempty(Aux)
        warndlg(['Selected folder doesn\''t contain SWAN output files\n' ...
            'Please select a folder with OUTPUT data.']);
        return
    end
else %project folder has not been selected. Exit function.
    return
end

SpcList={Aux.name};    
m_list=cell(1,length(SpcList)+1);
m_list{1}='Choose SWAN run...';

%load run list.
for j=1:length(SpcList)
    %remove subrun from run name (so it can be used as template).
    aux=regexp(SpcList{j},'01-','split','once');
    SpcList{j}=aux{2};
    aux=regexp(SpcList{j},'-H','split');
    aux=regexp(aux{2},'T','split');
    H=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'D','split');
    T=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'Lvl','split');
    D=str2double(regexprep(aux{1},'_','\.'));
    
    m_list{j+1}=sprintf('H: %s || T: %s || D: %s',H,T,dir2txt(D));
end

set(handles.CB_SwanRun,'String',m_list);
handles.m_SPC=SpcList;

%try to load computational grids' list
aux=regexp(SpcList{1},'-H','split');
aux=aux{1};
projName=aux(1:end-3); %last 3 characters is run number. Ignore that.
fName=fullfile(outputdir,[projName '.cgl']);
if exist(fName,'file')
    fh=fopen(fName);
    k=0;
    while ~feof(fh)
        k=k+1;
        line=fgetl(fh);
        gridList{k}=line;
    end
else
    %no grid list file, use numbers only.
    auxList=dir(fullfile(outputdir,['*-' SpcList{1}]));
    gridList=num2cell(1:length(auxList));
end
gridList={'Choose Grid...',gridList{:}};
set(handles.CB_CGrid,'String',gridList);


% Update handles structure
guidata(hObject, handles);

updateCPoints(handles);


% --- Executes on selection change in CB_SwanRun.
function CB_SwanRun_Callback(hObject, eventdata, handles)
% hObject    handle to CB_SwanRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

updateCPoints(handles);

% --- Executes during object creation, after setting all properties.
function CB_SwanRun_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_SwanRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in CB_CPoint.
function CB_CPoint_Callback(hObject, eventdata, handles)
% hObject    handle to CB_CPoint (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns CB_CPoint contents as cell array
%        contents{get(hObject,'Value')} returns selected item from CB_CPoint
%updateDisplay(handles);

% --- Executes during object creation, after setting all properties.
function CB_CPoint_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_CPoint (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in CB_CGrid.
function CB_CGrid_Callback(hObject, eventdata, handles)
% hObject    handle to CB_CGrid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

updateCPoints(handles);


% --- Executes during object creation, after setting all properties.
function CB_CGrid_CreateFcn(hObject, eventdata, handles)
% hObject    handle to CB_CGrid (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in PB_Update.
function PB_Update_Callback(hObject, eventdata, handles)
% hObject    handle to PB_Update (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if  isfield(handles,'pcontrol')

cla(handles.axes1,'reset');
cla(handles.axes3,'reset');

p=get(handles.CB_CPoint,'Value');

if p>1 %if it's not the fake string "choose position"
    p=p-1;
fr=handles.pcontrol{1}; %frequencies
th=handles.pcontrol{2}; %directions
th=th';

%SWAN gives negative angles. All should be positive.
for v=1:length(th)
    if th(v)<0
        th(v)=th(v)+360;
    end
end

%generate spectrum
f=fr*ones(size(th)); %frequency per direction matrix
t=ones(size(fr))*th; %directions per frequency matrix
spt=handles.pcontrol{4}{p};
dtype='met-N';

dth=abs(t(1,2)-t(1,1));
df=diff(fr);
nfr=length(fr);
fspt=(sum(spt,2)*dth)';
[fmax,kmax]=max(fspt); 
[smax,ktmax]=max(spt(kmax,:));
thmax=t(kmax,ktmax);
Hsig=4*sqrt(0.5*(fspt(1:nfr-1)*df+fspt(2:nfr)*df));
[z,ki]=max(spt);
[z,kj]=max(z);
Tp=1/f(ki(kj),kj);

%freq/dir rose

roseDSpt(handles.axes1,f,t*pi/180,spt,Tp,Hsig,thmax,'solid',dtype);
%freq/energy plot
plot(handles.axes3,f,fspt,'b','LineWidth',2); grid on;
set(handles.axes3, ...
    'Box'               , 'off'     , ...
    'TickDir'           , 'out'     , ...
    'TickLength'        , [.02 .02] , ...
    'XMinorTick'        , 'on'      , ...
    'YMinorTick'        , 'on'      , ...
    'YGrid'             , 'on'      , ...
    'XColor'            , [.3 .3 .3], ...
    'YColor'            , [.3 .3 .3], ...
    'XMinorGrid'        , 'on'      , ...
    'GridLineStyle'     , '--'      , ...
    'MinorGridLineStyle', ':'       , ...
    'LineWidth'         , 1         , ...
    'FontSize'          , 8         );
xlabel(handles.axes3,'f (Hz)','fontsi',10);
ylabel(handles.axes3,'E (m^2s)','fontsi',10)

X=handles.pcontrol{3}(p,1);
Y=handles.pcontrol{3}(p,2);
set(handles.TXT_XPos,'String',sprintf('X: %6.2f',X));
set(handles.TXT_YPos,'String',sprintf('Y: %6.2f',Y));

end
end

function updateCPoints(handles)

if  ~isempty(get(handles.CB_SwanRun,'String'))&...
    ~isempty(get(handles.CB_CGrid,'String')) %#ok<AND2>

    val=get(handles.CB_SwanRun,'Value');
    project=get(handles.TL_Project,'String');
    subrun=get(handles.CB_CGrid,'Value');
    
    if(val>1)&&(subrun>1) %ignore fake values
    
    SpcFile=fullfile(project,sprintf('%02d-%s',subrun-1,...
        handles.m_SPC{val-1}));
    
    handles.pcontrol=loadSWANPoints(SpcFile);
    
    nItem=length(handles.pcontrol{4});
    cpoints=num2cell(1:nItem);
    cpoints={'Choose Position...',cpoints{:}}; %#ok<CCAT>
    set(handles.CB_CPoint,'String',cpoints);
    
    set(handles.CB_CPoint,'Value',1);
    guidata(handles.figure1, handles);
    end
end
